package com.baimifan.renovation.manager;

import android.os.Handler;
import android.os.Message;

import com.baimifan.renovation.MyApplication;
import com.baimifan.renovation.model.TaskClassify;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

/**
 * Created by baimifan on 2017/07/04.
 */

public class TaskClassifyManager {
    private Handler mHandler;
    private String url = MyApplication.MAIN + "/index/index/first";
    private ArrayList<TaskClassify> lists = new ArrayList<>();

    public ArrayList<TaskClassify> getClassify () {
        return lists;
    }

    public TaskClassifyManager (Handler handler) {
        this.mHandler = handler;
    }

    /**
     * 获取首页任务分类
     */
    public void getTaskClassify () {
        RequestParams params = new RequestParams(url);
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                try {
                    if (result.getInt("status") == 200) {
                        JSONArray array = result.getJSONArray("data");
                        for (int i = 0; i < array.length(); i ++) {
                            TaskClassify task = new TaskClassify();
                            JSONObject data = array.getJSONObject(i);
                            if (!data.isNull("img")) {
                                task.setImg(MyApplication.MAIN + data.getString("img"));
                            }
                            if (!data.isNull("cat_name")) {
                                task.setCatName(data.getString("cat_name"));
                            }
                            if (!data.isNull("c_id")) {
                                task.setcId(data.getInt("c_id"));
                            }
                            lists.add(task);
                        }
                        Message msg = new Message();
                        msg.what = 2;
                        mHandler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
